/**
 *
 *@author ZhouLan
 *@version 1.0.0
 */

import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import hilog from '@ohos.hilog';
import UIAbility from '@ohos.app.ability.UIAbility';
import Want from '@ohos.app.ability.Want';
import window from '@ohos.window';
import {configs} from '../configs/Config'
import {ApplicationConfig} from '../entity/ApplicationConfig'
import {CartGoods} from '../entity/GlobalEntity'
import {Communications, Session, SessionMessage} from '../entity/Communications'
import {Request} from '../util/Requests'
import Address from '../entity/Address';

// let record:Record<string,Communications> = {'communications':new Communications()}
export default class EntryAbility extends UIAbility {
  storage:LocalStorage
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam):void{
    // console.log("size:"+this.storage.size())
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
    globalThis.context = this.context
    AppStorage.SetOrCreate<Communications>('communications',new Communications())
    AppStorage.SetOrCreate<number[]>('total',[])
    AppStorage.SetOrCreate<string[]>('currentOpposite',[''])
    AppStorage.SetOrCreate<boolean>('wsConnect',true)
    //应该是将communications全局变量加入到appStorage中
    //全局变量，在聊天窗口打开的时候，读取对应的聊天数据，离开时清空
    let applicationConfig:ApplicationConfig
    let httpUrl = configs.protocol.http+configs.domain+configs.port
    let wsUrl = configs.protocol.ws+configs.domain+configs.port
    globalThis.wsBaseUrl = wsUrl
    applicationConfig = new ApplicationConfig(wsUrl,httpUrl)
    globalThis.applicationConfig = applicationConfig
    globalThis.cartMap = new Map<string,CartGoods>()
    globalThis.request = new Request(httpUrl);
    console.log(`routerMap长度:${(globalThis.request as Request).getRoutersMap.length}`)
    //cartMap:Map<string,CartGoods>
    //当websocket打开时，可能会接收到数据，需要进行保存
    //有三种信息需要进行判断并分开进行存储
    //实际上客户端只能收到message和status两种信息
    // globalThis.communications = new Communications();
    //Communications中的两个数组将保存收到的来自服务器的信息，并在组件中渲染，globalThis适合用来存储静态数据，其中值的变化无法监测到
    //现在考虑以下操作:应用打开时，读取本地文件存储的信息，加载到全局对象中，再读取后续从socket接收到的信息
    //拼接到本地文件读取到的信息上，形成可以渲染的信息，每次有新的信息，都要执行此步骤，并重新渲染
    //每次关闭或者隐藏到后台时，对本地文件进行修改

    this.storage = new LocalStorage({'currentMessage':[] as SessionMessage[]})
    //这里的解决方案:如果说使用localStorage中的值对聊天窗口进行渲染，但是localStorage中的值不会因为改变而自动渲染，那么，可以
    //把接收到的值加入当前聊天页面的数组的，拟定使用@LocalStorage+@Link层层传递，进入一个聊天页面，就会在localStorage中传入当前聊天页面的id值
    //创建ws的函数在loading页面中定义，所以需要将这个值传递到loadingPage来进行判断

    //解决方案2：将要被渲染的页面的函数导出，这样就可以实现两个页面的沟通
    //不可行
  }
  onDestroy(): void {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
  }

  onWindowStageCreate(windowStage: window.WindowStage): void {
    // Main window is created, set main page for this ability
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');

    windowStage.getMainWindow((err,data)=>{
      if(err.code){
        console.log(err.message)
        return
      }
      globalThis.windowClass = data
    })
    //此函数第二个参数是要传递给ui的值
    windowStage.loadContent('pages/LoadingPage',this.storage, (err, data) => {
      if (err.code) {
        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
        return;
      }
      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
    });
  }

  onWindowStageDestroy(): void {
    // Main window is destroyed, release UI related resources
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
  }

  onForeground(): void {
    // Ability has brought to foreground
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
  }

  onBackground(): void {
    // Ability has back to background
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
    let communications = AppStorage.Get<Communications>('communications')
    communications.saveMessages()//保存内容到文件
  }
}
